package com.itheima.restkeeper.face;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.restkeeper.AffixFace;
import com.itheima.restkeeper.BrandFace;
import com.itheima.restkeeper.constant.SuperConstant;
import com.itheima.restkeeper.enums.BrandEnum;
import com.itheima.restkeeper.exception.ProjectException;
import com.itheima.restkeeper.pojo.Brand;
import com.itheima.restkeeper.req.AffixVo;
import com.itheima.restkeeper.req.BrandVo;
import com.itheima.restkeeper.service.IBrandService;
import com.itheima.restkeeper.utils.BeanConv;
import com.itheima.restkeeper.utils.EmptyUtil;
import com.itheima.restkeeper.utils.ExceptionsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.annotation.Method;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName BrandFaceImpl.java
 * @Description 品牌dubbo接口定义实现
 */
@DubboService(version = "${dubbo.application.version}", timeout = 5000,
        methods = {
                @Method(name = "findBrandVoPage", retries = 2),
                @Method(name = "createBrand", retries = 0),
                @Method(name = "updateBrand", retries = 0),
                @Method(name = "deleteBrand", retries = 0)
        })
@Slf4j
public class BrandFaceImpl implements BrandFace {

    @Autowired
    IBrandService brandService;

    @DubboReference(version = "${dubbo.application.version}", check = false)
    AffixFace affixFace;

    @Override
    public Page<BrandVo> findBrandVoPage(BrandVo brandVo,
                                         int pageNum,
                                         int pageSize) throws ProjectException {
        try {
            //查询Page<Brand>分页
            Page<Brand> page = brandService.findBrandVoPage(brandVo, pageNum, pageSize);
            //转化Page<Brand>为Page<BrandVo>
            Page<BrandVo> voPage = new Page<>();
            BeanConv.toBean(page, voPage);
            //转换List<Brand>为 List<BrandVo>
            List<Brand> brandList = page.getRecords();
            List<BrandVo> voList = BeanConv.toBeanList(brandList,BrandVo.class);

            //处理附件
            if (!EmptyUtil.isNullOrEmpty(voPage)&&!EmptyUtil.isNullOrEmpty(voList)){
                voList.forEach(n->{
                    List<AffixVo> affixVoList = affixFace.findAffixVoByBusinessId(n.getId());
                    if (!EmptyUtil.isNullOrEmpty(affixVoList)){
                        n.setAffixVo(affixVoList.get(0));
                    }
                });
            }

            //指定带有附件消息的brandVoList到pageVo中
            //返回结果
            voPage.setRecords(voList);
            return voPage;
        } catch (Exception e) {
            log.error("查询品牌列表异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.PAGE_FAIL);
        }
    }

    @Override
    public BrandVo createBrand(BrandVo brandVo) throws ProjectException {
        try {
            //保存品牌
            Brand brand = brandService.createBrand(brandVo);
            BrandVo vo = BeanConv.toBean(brand, BrandVo.class);

            //绑定附件
                //1.1根据附件消息查询当前的附件
            AffixVo voAffixVo = brandVo.getAffixVo();
            AffixVo affixVo=null;
            if (!EmptyUtil.isNullOrEmpty(vo)){

                 affixVo = affixFace.bindBusinessId(AffixVo.builder()
                        .businessId(vo.getId())
                        .id(brandVo.getAffixVo().getId()).build());

            }
            //1.2绑定business_id
            vo.setAffixVo(AffixVo.builder()
                    .businessId(vo.getId())
                    .id(brandVo.getAffixVo().getId())
                    .pathUrl(brandVo.getAffixVo().getPathUrl()).build());
            //返回结果
            return vo;
        } catch (Exception e) {
            log.error("保存品牌异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.CREATE_FAIL);
        }
    }

    @Override
    public Boolean updateBrand(BrandVo brandVo) throws ProjectException {
        try {
            //修改品牌
            Boolean aBoolean = brandService.updateBrand(brandVo);
            if (!aBoolean){
                return false;
            }
            //查询品牌附件消息
            List<AffixVo> affixVoList = affixFace.findAffixVoByBusinessId(brandVo.getId());
            List<Long> longs = affixVoList.stream().map(AffixVo::getId).collect(Collectors.toList());

            if (!longs.contains(brandVo.getAffixVo().getId())){
                //删除图片
                affixFace.deleteAffixVoByBusinessId(brandVo.getId());
            }
            //绑定新图片
            affixFace.bindBusinessId(AffixVo.builder()
                    .businessId(brandVo.getId())
                    .id(brandVo.getAffixVo().getId())
                    .build());
            if (EmptyUtil.isNullOrEmpty(affixVoList)){
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("修改品牌列表异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.UPDATE_FAIL);
        }
    }

    @Override
    public Boolean deleteBrand(String[] checkedIds) throws ProjectException {
        try {
            //删除品牌
            Boolean aBoolean = brandService.deleteBrand(checkedIds);

            //删除图片，是不是可以debug进去看看？
            for (String checkedId : checkedIds) {
                affixFace.deleteAffixVoByBusinessId(Long.valueOf(checkedId));
            }
            return aBoolean;
        } catch (Exception e) {
            log.error("删除品牌列表异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.DELETE_FAIL);
        }
    }

    @Override
    public BrandVo findBrandByBrandId(Long brandId) throws ProjectException {
        try {
            //查找品牌消息
            Brand brand = brandService.getById(brandId);
            BrandVo brandVo = BeanConv.toBean(brand, BrandVo.class);

            return brandVo;
        } catch (Exception e) {
            log.error("查找品牌所有品牌异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.SELECT_BRAND_FAIL);
        }
    }

    @Override
    public Boolean updateBrandEnableFlag(BrandVo brandVo) {
        try {
            //修改品牌状态
            Boolean aBoolean = brandService.updateBrandEnableFlag(brandVo);
            if (!aBoolean){
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("修改品牌状态异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.UPDATE_STATUS_FAIL);
        }
    }

    @Override
    public List<BrandVo> findBrandVoList() throws ProjectException {
        try {
            //查找品牌列表，用到哪里？要不要注意状态？
            LambdaQueryWrapper<Brand> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Brand::getEnableFlag, SuperConstant.YES);

            List<Brand> list = brandService.list(queryWrapper);
            List<BrandVo> brandVoList = BeanConv.toBeanList(list, BrandVo.class);

            return brandVoList;
        } catch (Exception e) {
            log.error("查询品牌列表异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(BrandEnum.PAGE_FAIL);
        }
    }
}
